<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>吃豆人游戏</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background: #87CEEB;
            font-family: Arial, sans-serif;
        }

        canvas {
            border: 3px solid #000;
            background: #ffffff;
        }

        #game-container {
            position: relative;
        }

        #score-board {
            position: absolute;
            top: 10px;
            left: 10px;
            color: #000;
            font-size: 18px;
            z-index: 1;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <div id="score-board">得分: 0</div>
        <canvas id="gameCanvas" width="800" height="600"></canvas>
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        let score = 0;
        const scoreBoard = document.getElementById('score-board');
        
        // 吃豆人属性
        const pacman = {
            x: 50,
            y: 50,
            radius: 20,
            speed: 5,
            dx: 0,
            dy: 0
        };

        // 豆子数组
        let beans = [];
        
        // 更新分数
        function updateScore(points) {
            score += points;
            scoreBoard.textContent = `得分: ${score}`;
            // 确保分数显示在画布上
            ctx.fillStyle = '#fff';
            ctx.font = '18px Arial';
            ctx.fillText(`得分: ${score}`, 10, 30);
        }

        // 绘制吃豆人
        function drawPacman() {
            ctx.save();
            ctx.translate(pacman.x, pacman.y);
            
            // 计算旋转角度
            if (pacman.dx !== 0 || pacman.dy !== 0) {
                const angle = Math.atan2(pacman.dy, pacman.dx);
                ctx.rotate(angle);
            }
            
            ctx.beginPath();
            ctx.arc(0, 0, pacman.radius, 0.25 * Math.PI, 1.75 * Math.PI);
            ctx.lineTo(0, 0);
            ctx.fillStyle = 'yellow';
            ctx.fill();
            ctx.closePath();
            
            ctx.restore();
        }

        // 创建豆子
        function createBean() {
            const colors = ['red', 'green', 'blue', 'yellow', 'purple', 'orange'];
            const color = colors[Math.floor(Math.random() * colors.length)];
            
            beans.push({
                x: Math.random() * (canvas.width - 20) + 10,
                y: Math.random() * (canvas.height - 20) + 10,
                radius: 5,
                captured: false,
                color: color
            });
        }

        // 绘制豆子
        function drawBeans() {
            for (const bean of beans) {
                if (!bean.captured) {
                    ctx.beginPath();
                    ctx.arc(bean.x, bean.y, bean.radius, 0, Math.PI * 2);
                    ctx.fillStyle = bean.color;
                    ctx.fill();
                    ctx.closePath();
                }
            }
        }

        // 检测碰撞
        function checkCollision() {
            for (let i = 0; i < beans.length; i++) {
                const bean = beans[i];
                const distance = Math.sqrt((pacman.x - bean.x) ** 2 + (pacman.y - bean.y) ** 2);
                if (distance < pacman.radius + bean.radius) {
                    bean.captured = true;
                    updateScore(1);
                    
                    // 吃到豆子后吃豆人变大
                    pacman.radius += 1; // 每吃一个豆子，半径增加1
                }
            }
            
            // 判断是否胜利（当分数达到70时）
            if (score >= 70) {
                showVictoryScreen();
                return;
            }
        }

        // 显示胜利界面
        function showVictoryScreen() {
            // 先清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制黑色背景
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制文字
            ctx.fillStyle = '#fff';
            ctx.font = '48px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('你赢了！', canvas.width / 2, canvas.height / 2 - 40);
            
            ctx.font = '24px Arial';
            ctx.fillText('再来一局', canvas.width / 2, canvas.height / 2 + 40);
            
            // 确保按钮点击有效
            canvas.addEventListener('click', restartGame, { once: true });
        }

        // 重新开始游戏
        function restartGame() {
            // 重置吃豆人属性
            pacman.radius = 20;
            pacman.x = 50;
            pacman.y = 50;
            pacman.dx = 0;
            pacman.dy = 0;
            
            // 重置分数
            score = 0;
            scoreBoard.textContent = `得分: ${score}`;
            
            // 清空豆子并重新生成
            beans = [];
            for (let i = 0; i < 10; i++) {
                createBean();
            }
            
            // 隐藏胜利界面
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            gameLoop();
        }

        // 更新游戏状态
        function updateGame() {
            pacman.x += pacman.dx;
            pacman.y += pacman.dy;

            // 边界检测
            if (pacman.x + pacman.radius > canvas.width) pacman.x = pacman.radius;
            if (pacman.x - pacman.radius < 0) pacman.x = canvas.width - pacman.radius;
            if (pacman.y + pacman.radius > canvas.height) pacman.y = pacman.radius;
            if (pacman.y - pacman.radius < 0) pacman.y = canvas.height - pacman.radius;

            checkCollision();

            // 动态刷新豆子：当豆子数量少于5个时，生成新的豆子
            if (beans.filter(bean => !bean.captured).length < 5) {
                for (let i = 0; i < 5; i++) {
                    createBean();
                }
            }

            beans = beans.filter(bean => !bean.captured); // 更新原数组
        }

        // 绘制游戏
        function drawGame() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#000';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            drawPacman();
            drawBeans();
            // 确保分数显示在画布上
            ctx.fillStyle = '#fff';
            ctx.font = '18px Arial';
            ctx.fillText(`得分: ${score}`, 10, 30);
        }

        // 游戏循环
        function gameLoop() {
            updateGame();
            drawGame();
            requestAnimationFrame(gameLoop);
        }

        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (e.code === 'ArrowUp') {
                pacman.dx = 0;
                pacman.dy = -pacman.speed;
            } else if (e.code === 'ArrowDown') {
                pacman.dx = 0;
                pacman.dy = pacman.speed;
            } else if (e.code === 'ArrowLeft') {
                pacman.dx = -pacman.speed;
                pacman.dy = 0;
            } else if (e.code === 'ArrowRight') {
                pacman.dx = pacman.speed;
                pacman.dy = 0;
            }
        });

        // 启动游戏
        function startGame() {
            // 在游戏开始时生成10个豆子
            for (let i = 0; i < 10; i++) {
                createBean();
            }
            
            // 延迟创建音频元素以确保页面加载完成
            const bgMusic = document.createElement('audio');
            bgMusic.id = 'background-music';
            bgMusic.src = '333.mp3';
            bgMusic.loop = true;
            bgMusic.volume = 0.9;
            bgMusic.preload = 'auto';
            
            // 添加音频加载和错误监听器
            bgMusic.addEventListener('canplaythrough', () => console.log('音频已加载完成，可以流畅播放'));
            bgMusic.addEventListener('error', (e) => console.error('音频加载失败:', e));
            bgMusic.addEventListener('ended', () => console.log('音频播放结束'));
            
            document.body.appendChild(bgMusic);
            
            // 尝试播放音乐并处理用户交互需求
            bgMusic.play().catch(err => {
                console.log('音乐播放被浏览器阻止，等待用户交互...');
                // 添加点击事件以在用户交互后播放音乐
                document.addEventListener('click', () => {
                    bgMusic.play().catch(err => console.log('音乐播放失败:', err));
                }, { once: true });
            });
            
            gameLoop();
        }

        // 开始游戏
        startGame();
    </script>
</body>
</html>